import { Redirect } from "react-router-dom"
import { connect } from "react-redux"

// 路由守卫
const AuthRoute = ({ history, location, match, userInfo, children }) => {
  const { pathname } = location

  // 1. 如果用户未登录，访问了主页
  if (pathname.startsWith("/home") && !sessionStorage.getItem("token")) {
    return <Redirect to="/login" />
  }

  // 2. 如果已登陆，用户访问了登陆页，进行路由拦截，回到主页
  if (pathname === "/login" && sessionStorage.getItem("token")) {
    return <Redirect to="/home" />
  }

  // 3. 如果role >= 4,则该用户没有用户管理权限，则不允许跳转到 /home/user-center
  if (pathname === "/home/user-panel" && userInfo.role >= 4) {
    return <Redirect to="/home/user-center" />
  }

  return <>{children}</>
}

const connector = connect((state) => ({ userInfo: state }))

export default connector(AuthRoute)
